<?php

namespace frontend\modules\shop\controllers;

use common\components\Category;
use common\components\Upload;
use common\models\business\BusinessUser;
use common\models\shop\ShopComment;
use common\models\shop\ShopGoods;
use common\models\shop\ShopGoodsCategory;
use common\models\shop\ShopOrderGoods;
use common\models\business\BusinessPig;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Response;

/**
 * Class OrderController
 * @package frontend\modules\shop\controllers
 * 商品相关控制器
 */
class GoodsController extends BaseMobileController
{

    /**
     * @param $cid
     * @return string
     * 列表页
     */
    public function actionList($cid)
    {
        $cate = ShopGoodsCategory::find()->select('name,id,parentid')->where('enabled=:status',[':status'=>ShopGoodsCategory::ENABLE_ACTIVE])->asArray()->all();
        foreach ($cate as $key => $row)
        {
            $cate[$key]['url'] = Url::to(['/shop/goods/list','cid'=>$row['id']]);
        }

        $cate = Category::getTree($cate);

        $query = ShopGoods::find()->select('unit,weight,thumb as img,id,title,originalprice as o_price,productprice as price,total as nums,displayorder')
            ->where('cateid=:cid and status=:status',[':cid'=>$cid,':status'=>ShopGoods::STATUS_ACTIVE])
            ->limit(20);

        $by = \Yii::$app->request->get('by');

        if($by == 'num'){
            $goods = $query->orderBy('sales desc')->asArray()->all();
        }else if($by == 'price'){
            $goods = $query->orderBy('price asc')->asArray()->all();
        }else{
            $goods = $query->asArray()->orderBy('displayorder asc')->all();
        }

        foreach ($goods as $key => $row)
        {
            $goods[$key]['img'] = Upload::checkGetUrl($row['img']);
            $goods[$key]['url'] = Url::to(['/shop/goods/detail','gid'=>$row['id']]);
        }

        return $this->render('@template/mobile/list.html',[
            'goods' => \GuzzleHttp\json_encode($goods),
            'cate' => \GuzzleHttp\json_encode($cate),
            'cid' => $cid,
            'by' => \Yii::$app->request->get('by'),
        ]);
    }


    /**
     * 商品加载更多
     */
    public function actionLoadMore()
    {
        $cid = \Yii::$app->request->post('cid');
        $pindex = \Yii::$app->request->post('pindex');
        $pindex = $pindex?$pindex:1;
        $pagesize = 10;

        $query = ShopGoods::find()->select('unit,weight,thumb as img,id,title,originalprice as o_price,productprice as price,total as nums')
            ->where('cateid=:cid',[':cid'=>$cid])
            ->limit($pagesize)->offset(($pindex)*$pagesize);

        $by = \Yii::$app->request->get('by');
        if($by == 'price'){
            $goods = $query->orderBy('price asc')->asArray()->all();
        }else if($by == 'num'){
            $goods = $query->orderBy('sales desc')->asArray()->all();
        }else if($by == 'comment'){
            $goods = $query->orderBy('sales desc')->asArray()->all();
        }else{
            $goods = $query->asArray()->all();
        }

        foreach ($goods as $key => $row)
        {
            $goods[$key]['img'] = Upload::checkGetUrl($row['img']);
            $goods[$key]['url'] = Url::to(['/shop/goods/detail','gid'=>$row['id']]);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $goods;
    }



    /**
     * @param $gid
     * @return string
     * 商品详情页
     */
    public function actionDetail($gid)
    {

        $goods = ShopGoods::find()->select('unit,isprebuy,weight,mutithumb,pigid,total,thumb as img,id,title,content as article,originalprice as o_price,productprice as price,total as nums')
            ->where('id=:id',[':id'=>$gid])
            ->asArray()
            ->one();

        $goods['img'] = Upload::checkGetUrl($goods['img']);


        $pigno = BusinessPig::find()->select('no')->where('id=:id',[':id'=>$goods['pigid']])->asArray()->one();


        $comment = ShopComment::find()
            ->alias('c')
            ->leftJoin(BusinessUser::tableName().' as u','userid=u.id')
            ->select('star,content,FROM_UNIXTIME(c.createtime) as time,u.avatar as headimg,u.nickname as name,picture')
            ->where('c.status=:status and goodsid=:id',[':status'=>ShopComment::STATUS_AGREE,':id'=>$gid])
            ->asArray()
            ->all();
        foreach ($comment as $key => $row)
        {
            $comment[$key]['picture'] = Upload::checkGetUrl($row['picture'],true,'picture',false);
        }

        $goods['text'] = '';

        $goods['comment'] = $comment;


        $banner = Upload::checkGetUrl($goods['mutithumb'],true);

        return $this->render('@template/mobile/detail.html',[
            'detail' => \GuzzleHttp\json_encode($goods),
            'pigid' => $goods['pigid'],
            'banner' => \GuzzleHttp\json_encode($banner),
            'pigno' => $pigno['no'],
            'goods' => $goods
        ]);
    }


    /**
     * @param $gid
     * @return string
     * 限时商品详情
     */
    public function actionTimeDetail($gid)
    {
        $goods = ShopGoods::find()->select('weight,mutithumb,pigid,thumb as img,id,title,content as article,originalprice as o_price,productprice as price,total as num,timestart,timeend')
            ->where('id=:id',[':id'=>$gid])
            ->asArray()
            ->one();
        $goods['timestart'] = date('Y-m-d H:i:s');
        $goods['timeend'] = date('Y-m-d H:i:s',$goods['timeend']);
        $goods['thumb'] = Upload::checkGetUrl($goods['img']);


        $comment = ShopComment::find()
            ->alias('c')
            ->leftJoin(BusinessUser::tableName().' as u','userid=u.id')
            ->select('picture,content,FROM_UNIXTIME(c.createtime) as time,u.avatar as headimg,u.nickname as name')
            ->where('goodsid=:gid',[':gid'=>$gid])
            ->asArray()
            ->all();
        if($comment){
            foreach ($comment as $key => $row)
            {
                $comment[$key]['picture'] = Upload::checkGetUrl($row['picture'],true,'picture',false);
            }
        }

        $goods['text'] = '';

        $goods['comment'] = $comment;


        $banner = Upload::checkGetUrl($goods['mutithumb'],true);

        return $this->render('@template/mobile/pig_detail.html',[
            'detail' => \GuzzleHttp\json_encode($goods),
            'pigid' => $goods['pigid'],
            'goods' => $goods,
            'banner' => \GuzzleHttp\json_encode($banner)
        ]);
    }





    /**
     * 评价页面
     */
    public function actionComment($id,$oid)
    {
        $goodsinfo = ShopGoods::find()
            ->select('id,title,description,productprice,unit')
            ->where('id=:id',[':id'=>$id])
            ->asArray()
            ->one();
        $goodsinfo['content'] = $goodsinfo['productprice'].'/'.$goodsinfo['unit'];

        return $this->render('@template/mobile/comment.html',[
            'goodsinfo' => \GuzzleHttp\json_encode($goodsinfo),
            'oid' => $oid,
            ]);
    }


    /**
     * 提交评价
     */
    public function actionPostComment()
    {
        $postdata = \Yii::$app->request->post();
        $data = [
            'star' => intval($postdata['score']),
            'content' => $postdata['conmment'],
            'createtime' => time(),
            'userid' => $this->user['userid'],
            'openid' => $this->user['openid'],
            'goodsid' => $postdata['id'],
        ];
        if($postdata['img']){
            $infoimgs = Upload::uploadBase64($postdata['img']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($farmer['img'])){
                $infoimgs = $farmer['img'].'|'.$infoimgs;
            }
            $data['picture'] = $infoimgs;
        }
        $res = \Yii::$app->db->createCommand()->insert(ShopComment::tableName(),$data)->execute();

        //更新评价状态
        $res = \Yii::$app->db->createCommand()
            ->update(ShopOrderGoods::tableName(),['iscomment'=>1],'goodsid=:goodsid and orderid=:oid',[':goodsid'=>$postdata['id'],':oid'=>$postdata['oid']])
            ->execute();

        return $res?$this->jsonMsg('评价成功',0):$this->jsonMsg('评价失败',1);
    }





}

